package com.hj.factory;

import com.hj.constants.CaptchaConstants.CaptchaTypeEnum;
import com.hj.service.CaptchaService;
import com.hj.util.SpringUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author doudh
 * @date 2020/8/25
 * @description 验证码类型实现类工厂
 */
public class CaptchaTypeFactory {
    private static Map<String, CaptchaService> captchaServiceBeanMap = new ConcurrentHashMap();

    public static void init() {
        if (captchaServiceBeanMap.size() == 0) {
            for (CaptchaTypeEnum e : CaptchaTypeEnum.values()) {
                String serviceBeanName = CaptchaTypeEnum.getServiceBeanName(e.getCodeValue());
                captchaServiceBeanMap.put(serviceBeanName, SpringUtils.getBean(serviceBeanName));
            }
        }
    }

    public static CaptchaService getCaptchaService(String captchaType) {
        try {
            if (StringUtils.isEmpty(captchaType)) {
                return null;
            }
            String beanName = CaptchaTypeEnum.getServiceBeanName(captchaType);
            if (StringUtils.isEmpty(beanName)) {
                return null;
            }
            CaptchaService captchaService = captchaServiceBeanMap.get(beanName);
            if (captchaService != null) {
                return captchaService;
            }
            captchaService = SpringUtils.getBean(CaptchaTypeEnum.getServiceBeanName(captchaType));
            captchaServiceBeanMap.put(beanName, captchaService);
            return captchaService;
        } catch (Exception e) {
            return null;
        }
    }
}
